package cn.edu.swu.auth;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;
import org.apache.commons.codec.digest.DigestUtils;

import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.atomic.AtomicReference;


public class UserLoginService {

    private UserRepo userRepo;

    public UserLoginService(UserRepo userRepo) {
        this.userRepo = userRepo;
    }

    public boolean authenticateUser(String username, String password, String authCode, HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {

        HttpSession session = request.getSession(false);
        if (session == null || !authCode.equalsIgnoreCase((String) session.getAttribute(AuthCodeServlet.AUTH_CODE))) {
            request.setAttribute("loginError", "验证码错误");
            return false;
        }

        String sql = "SELECT uid, username, userPwd FROM usermsg WHERE username = ?";
        return userRepo.query(sql, ps -> {
            try {
                ps.setString(1, username);
                ResultSet rs = ps.executeQuery();
                if (!rs.next()) {

                    request.setAttribute("loginError", "用户名不存在");
                    return false;
                }

                String storedPassword = rs.getString("userPwd");
                // 加密用户输入的密码并与数据库中的密码进行对比
                String encryptedPassword = DigestUtils.md5Hex(password);
                if (encryptedPassword.equals(storedPassword)) {
                    // 登录成功逻辑
                    HttpSession httpSession = request.getSession(true);
                    httpSession.setAttribute("uid", rs.getInt("uid")); // 存储uid到会话中
                    return true;
                } else {

                    request.setAttribute("loginError", "密码错误");
                    return false;
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        });
    }

}
